import { useIntl, useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { ConfigProvider, Flex, Table } from 'antd';
import React from 'react';
import { Link } from 'umi';

import Card from '@/components/Card';
import {
  mainPageControllerGetEventDatas,
  mainPageControllerGetEventInfoTypeCount,
} from '@/services/ess/mainpageStation';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';

export interface IDataSourceItem extends API.EventDataVO {
  serialNumber: number;
  gradeLabel: string | undefined;
}

export const BatteryEvents: React.FC = React.memo(() => {
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();

  const LEVEL_COLOR_MAP: Record<number, string> = {
    1: '#F54E4B',
    2: '#FF7A0C',
    3: '#FFD50C',
  };

  const STATE_COLOR_MAP: Record<string, string> = {
    [intl.formatMessage({ id: 'global.accident' })]: '#F54E4B',
    [intl.formatMessage({ id: 'global.alarm' })]: '#FF7A0C',
    [intl.formatMessage({ id: 'global.notice' })]: '#FFD50C',
  };

  const EVENT_GRADES = [
    {
      level: 1,
      description: intl.formatMessage({ id: 'global.accident' }),
    },
    {
      level: 2,
      description: intl.formatMessage({ id: 'global.alarm' }),
    },
    {
      level: 3,
      description: intl.formatMessage({ id: 'global.notice' }),
    },
  ];

  const { data = {} } = useRequest(
    () => mainPageControllerGetEventDatas({ type: '2', size: '10' }),
    {
      refreshDeps: [initialState?.stationId],
    },
  );

  const { data: eventTypeCountResult = {} } = useRequest(mainPageControllerGetEventInfoTypeCount, {
    refreshDeps: [initialState?.stationId],
  });

  const { data: eventGradeDictList = [] } = useRequest(() =>
    fetchDictInfo(DATABASE_TYPE_ENUM.EVENT_GRADE),
  );

  const eventTypeCountList = eventTypeCountResult.data ?? [];

  const dataSource =
    data.data?.map((item, index) => ({
      ...item,
      serialNumber: index + 1,
      gradeLabel: item.state,
    })) || [];

  const columns = [
    {
      title: intl.formatMessage({ id: 'global.s/N' }), // 使用国际化的字段
      dataIndex: 'serialNumber',
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'global.grade' }),
      dataIndex: 'gradeLabel',
      width: 80,
      render: (text: string, record: IDataSourceItem) => (
        <span style={{ color: STATE_COLOR_MAP[String(record.state)] }}>{text}</span>
      ),
    },
    {
      title: intl.formatMessage({ id: 'global.eventDescription' }),
      dataIndex: 'desc',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'global.locationID' }),
      dataIndex: 'location',
      ellipsis: true,
    },
  ];

  return (
    <Card
      title={intl.formatMessage({ id: 'overviewPages.batteryEvents' })}
      extra={
        <Flex align="center">
          <div style={{ display: 'flex' }}>
            {EVENT_GRADES.map((item) => {
              const label = eventGradeDictList.find(
                (dict) => Number(dict.value) === item.level,
              )?.label;
              const count = eventTypeCountList.find(
                (count) => Number(count.eventType) === item.level,
              )?.total;
              return (
                <div
                  key={item.level}
                  style={{
                    flex: 1,
                    backgroundColor: LEVEL_COLOR_MAP[item.level],
                    minWidth: 'fit-content',
                    height: '20px',
                    padding: '0 4px',
                    lineHeight: '20px',
                    fontSize: '12px',
                    color: '#FFFFFF',
                    textAlign: 'center',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {label ?? item.description} {Number(count) > 99 ? '99+' : count}
                </div>
              );
            })}
          </div>
          <Link to={'/alarm/list'} style={{ marginLeft: '20px', cursor: 'pointer' }}>
            <span style={{ color: '#000022', fontSize: '12px' }}>
              {intl.formatMessage({ id: 'global.detail' })}
            </span>
            <span style={{ marginLeft: '1px', color: ' #999999' }}>{'>'}</span>
          </Link>
        </Flex>
      }
      style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
      styles={{
        body: {
          flex: 1,
        },
      }}
    >
      <ConfigProvider
        theme={{
          components: {
            Table: {
              cellPaddingBlock: 8,
              cellFontSize: 12,
              algorithm: true,
            },
          },
        }}
      >
        <Table
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          scroll={{ y: 106 }}
        />
      </ConfigProvider>
    </Card>
  );
});
